package arrAndstr;

/*
    48. 旋转图像
    优化空间：
        不用boolean矩阵：
            外层循环 n/2
            内层循环 (n+1)/2
        因为每次循环4个，所以只需要左半部分的1/4 --> 画图很清晰
 */
public class T48 {
    public static void main(String[] args) {
        int[][] array = new int[][]{
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };
        rotate(array);
        for (int i=0; i<array.length; i++) {
            for (int j=0; j<array[0].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void rotate(int[][] matrix) {
        int row = matrix.length;
        int column = matrix[0].length;
        boolean[][] isChange = new boolean[row][column];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (!isChange[i][j]) {
                    startRotate(matrix, isChange, i, j);
                }
            }
        }
    }

    private static void startRotate(int[][] matrix, boolean[][] isChange, int i, int j) {
        isChange[i][j] = true;
        int n = matrix.length-1;
        int temp = matrix[i][j];
        int rowIndex = j;
        int columnIndex = n-i;
        while (rowIndex!=i || columnIndex!=j) {
            isChange[rowIndex][columnIndex] = true;
            int newTemp = matrix[rowIndex][columnIndex];
            matrix[rowIndex][columnIndex] = temp;
            temp = newTemp;

            int originRowIndex = rowIndex;
            int originColumnIndex = columnIndex;

            rowIndex = originColumnIndex;
            columnIndex = n-originRowIndex;
        }
        matrix[i][j] = temp;
    }


}
